<script lang="ts" setup name="UserServiceIndex">
import { onMounted, reactive, ref, nextTick, Ref } from "vue";
import { ElNotification, ElMessage, ElMessageBox } from "element-plus";
import { CirclePlus, Edit, Delete, ArrowDown } from "@element-plus/icons-vue";
import { ReturnTree, messageWarnTip } from "@whjxtech/jxtech-component";
import UserList from "./component/user-list.vue";
import UnitTreeCard from "@/views/org/unit/component/unit-tree-card.vue";
import unitServiceApi from "@/api/modules/org/bean/unit";
import userServiceApi from "@/api/modules/org/bean/user-bean";
import { downloadFile } from "@/utils/file";
import UserListSelectDialog from "./component/user-list-select-dialog.vue";
import UserDeptServiceApi from "@/api/modules/org/bean/user-dept";
import unitFormDialog from "@/views/org/unit/component/unit-form-dialog.vue";
import { messageInfoTip, messageSuccessTip } from "@/utils/message-config";
import { unitTreeServiceApi } from "@/api/modules/org/bean/tree-service";
import { AxiosResponse } from "axios";
// import baseCustomUnit from "/@/api/base/bean/bese-custom-unit"
let ids: Ref<Array<any>> = ref([]);
const UnitTreeCardRef = ref();
const UserListRef = ref();
const UserState = reactive({
  currentNode: null,
  queryParam: { unitId: "10000", id: "10000", subOrgId: "10000" },
  loadUserTable: () => {
    UserListRef.value.getUserListTableRef().loadTable();
  },
  /**节点点击事件 */
  handleNodeClick: (treeData: ReturnTree<any>) => {
    console.log("tree", treeData);
    UserState.queryParam.unitId = treeData.id;
    UserState.queryParam.id = treeData.attributes.orgId;
    UserState.queryParam.subOrgId = treeData.attributes.subOrgId;
    nextTick(() => UserState.loadUserTable());
  },
  onAddButtonClick: () => {
    UserListRef.value.onAddButtonClick();
  },
  onDeleteButtonClick: () => {
    UserListRef.value.onDeleteButtonClick();
  },
  // 关联用户
  onRelUserClick: () => {
    RelUserState.userDialogVisible = true;
  },
  //下载按钮loading
  downloadButtonLoading: false,
  //下载附件模板
  onDownloadButtonClick: (type: string, name: string) => {
    UserState.downloadButtonLoading = true;
    unitServiceApi
      .downloadExcelTemplate(type)
      .then(res => {
        downloadFile(res, `${name}.xlsx`);
      })
      .finally(() => {
        UserState.downloadButtonLoading = false;
      });
  },
  dialogVisible: false,
  uploadExcelUrl: "",
  //导入按钮下拉点击事件
  handleCommand: (command: string | number | object) => {
    if (command == "download-unit") {
      UserState.onDownloadButtonClick("unit", "部门导入模板");
    } else if (command == "upload-unit") {
      UserState.uploadExcelUrl = unitServiceApi.getImportExcelUrl();
      UserState.dialogVisible = true;
    } else if (command == "download-user") {
      UserState.onDownloadButtonClick("user", "用户导入模板");
    } else if (command == "upload-user") {
      UserState.uploadExcelUrl = userServiceApi.getImportExcelUrl();
      UserState.dialogVisible = true;
    }
  },
  //上传附件
  onUploadButtonClick: (type: string) => {
    if (type == "unit") {
      UserState.uploadExcelUrl = unitServiceApi.getImportExcelUrl();
    } else if (type == "user") {
      UserState.uploadExcelUrl = userServiceApi.getImportExcelUrl();
    }
    UserState.dialogVisible = true;
  },
  importSuccess: () => {
    UserState.loadUserTable();
  },
  // 部门树相关操作
  visibleUnitDialog: false, // 编辑部门树
  unitId: "", // 当前部门节点id
  parentUnitId: "", // 当前部门节点父级id
  onAddButtonItem: (row: any, node: any) => {
    UserState.currentNode = node;
    UserState.unitId = "";
    UserState.parentUnitId = row.id;
    UserState.visibleUnitDialog = true;
  },
  onEditButtonItem: (row: any, node: any) => {
    UserState.currentNode = node;
    UserState.unitId = row.id;
    UserState.parentUnitId = "";
    UserState.visibleUnitDialog = true;
  },
  onDeleteButtonItem: (row: any, node: any) => {
    UserState.currentNode = node;
    ElMessageBox.confirm("此操作将永久删除选中的数据, 是否继续?", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
      lockScroll: false
    })
      .then(() => {
        ids.value.push(row.id);
        unitTreeServiceApi.saveMultiDelete(ids.value).then((_Response: AxiosResponse) => {
          UserState.currentNode.parent.loaded = false;
          UserState.currentNode.parent.loadData();
          UserState.currentNode = null;
          ElNotification({
            title: "删除成功",
            type: "success"
          });
        });
      })
      .catch(() => {
        UserState.currentNode = null;
        messageInfoTip("已取消删除!");
      });
  },
  onSaveSuccess: (_formData: any, _res: any) => {
    // console.log("最外层", formData, res)
    // UnitTreeCardRef.value.ExposeRefresh()
    UserState.currentNode.loaded = false;
    UserState.currentNode.loadData();
    UserState.currentNode.parent.loaded = false;
    UserState.currentNode.parent.loadData();
    UserState.currentNode = null;
  }
});

const RelUserState = reactive({
  userDialogVisible: false,
  userDialogActiveUserId: "",
  userDialogActiveUserText: "",
  onSelectClick: () => (RelUserState.userDialogVisible = true),
  onFinish: (ids: string) => {
    if (!ids) {
      messageWarnTip("请至少选择一个用户");
    }
    UserDeptServiceApi.associateDeptUser({
      deptId: UserState.queryParam.unitId,
      userIds: ids
    }).then((res: any) => {
      if (res.data.success) {
        ElMessage({
          type: "success",
          message: "操作成功"
        });
        RelUserState.userDialogVisible = false;
        UserState.loadUserTable();
      }
    });
  }
});

onMounted(() => UserState.loadUserTable());
</script>
<template>
  <div class="UserServiceIndex">
    <jxtech-customs-container>
      <template #left-container>
        <unit-tree-card ref="UnitTreeCardRef" @node-click="UserState.handleNodeClick" class="">
          <template #default="{ row, node }">
            <div class="app-menu-tree-table-control">
              <span @click.stop="UserState.onAddButtonItem(row, node)" title="新增部门">
                <el-icon color="#409eff">
                  <circle-plus />
                </el-icon>
              </span>
              <span @click.stop="UserState.onEditButtonItem(row, node)" title="编辑部门">
                <el-icon color="#67c23a">
                  <edit />
                </el-icon>
              </span>
              <span v-if="!row.isParent" @click.stop="UserState.onDeleteButtonItem(row, node)" title="删除部门">
                <el-icon color="#f56c6c">
                  <delete />
                </el-icon>
              </span>
            </div>
          </template>
        </unit-tree-card>
      </template>
      <template #right-container>
        <user-list
          ref="UserListRef"
          :query-param="UserState.queryParam"
          @on-rel-user-click="UserState.onRelUserClick"
          @handle-command="UserState.handleCommand"
        ></user-list>
      </template>
    </jxtech-customs-container>
    <!-- <el-row>
    <el-col :span="6">
      <unit-tree-card ref="UnitTreeCardRef" @node-click="UserState.handleNodeClick" class="jxtech-main-mr">
        <template #default="{ row, node }">
          <div class="app-menu-tree-table-control">
            <span @click.stop="UserState.onAddButtonItem(row, node)" title="新增部门">
              <el-icon color="#409eff">
                <circle-plus />
              </el-icon>
            </span>
            <span @click.stop="UserState.onEditButtonItem(row, node)" title="编辑部门">
              <el-icon color="#67c23a">
                <edit />
              </el-icon>
            </span>
            <span v-if="!row.isParent" @click.stop="UserState.onDeleteButtonItem(row, node)" title="删除部门">
              <el-icon color="#f56c6c">
                <delete />
              </el-icon>
            </span>
          </div>
        </template>
      </unit-tree-card>
    </el-col>
    <el-col :span="18">
      <user-list
        ref="UserListRef"
        :query-param="UserState.queryParam"
        @onRelUserClick="UserState.onRelUserClick"
        @handleCommand="UserState.handleCommand"
      ></user-list>
    </el-col>
  </el-row> -->
    <!-- <jxtech-import-dialog
      v-if="UserState.dialogVisible"
      v-model:visible="UserState.dialogVisible"
      :action="UserState.uploadExcelUrl"
      @import-success="UserState.importSuccess"
    ></jxtech-import-dialog> -->

    <JxtechUserDialogExt
      :multiple="true"
      v-model:visible="RelUserState.userDialogVisible"
      v-model:select-user-ids="RelUserState.userDialogActiveUserId"
      v-model:select-user-texts="RelUserState.userDialogActiveUserText"
      @finish="RelUserState.onFinish"
    ></JxtechUserDialogExt>
    <!-- <user-list-select-dialog
    v-model:visible="UserState.visibleDialog"
    :unit-id="UserState.queryParam.unitId"
    @ok="UserState.saveSuccess"
  >
  </user-list-select-dialog> -->
    <unit-form-dialog
      v-model:visible="UserState.visibleUnitDialog"
      :unit-id="UserState.unitId"
      :parent-unit-id="UserState.parentUnitId"
      @save-success="UserState.onSaveSuccess"
    >
    </unit-form-dialog>
  </div>
</template>

<style scoped lang="scss">
.app-menu-tree-table-control {
  display: none;
  align-items: center;
  justify-content: center;
  font-size: 18px;
  > span {
    display: inherit;
    margin-left: 12px;
    cursor: pointer;
  }
}
.el-tree-node__content:hover {
  .app-menu-tree-table-control {
    display: flex;
  }
}
</style>
